const App = getApp();
const db = wx.cloud.database();
const _ = db.command;
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 新增附件按钮
    btnloading: false,
    // 班级弹窗
    show: false,
    loading: true,
    // 班级单选框
    radio: '',
    // 文件夹单选框
    folderRadio: 'Public',
    className: "",
    // 搜索到的班级
    class: [],
    periods: "",
    // 创建课程
    folder: {
      name: "",
      className: "",
      classId: null,
      members: [],
      category: "" || 'Public',
      file: [],
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    let getopenid = App.cache.getOpenID()
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo: UserInfo,
      getopenid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 打开弹窗
  showPopup() {
    wx.hideKeyboard()
    this.setData({
      show: true
    });

    this.getMyclass()
  },
  // 关闭弹窗
  onClosePopup() {
    this.setData({
      show: false
    });
  },
  // 文件夹类别
  onChange(event) {
    console.log('文件夹类别', event.detail);
    this.setData({
      folderRadio: event.detail,
      'folder.category': event.detail
    });
    if (event.detail === 'Public') {
      this.setData({
        radio: "",
        className: "",
        ['folder.className']: "",
        ['folder.classId']: null,
        ['folder.members']: [],
      })
    }
  },
  // 班级单选框
  onChangeradio(event) {
    this.setData({
      radio: event.detail,
    });
  },
  // 单选框
  onClickradio(event) {
    let data = event.currentTarget.dataset;
    console.log('data', data);
    console.log('当前选中的班级的id：', data.value);
    console.log('当前选中的班级的名称：', data.name);
    this.setData({
      radio: data.value,
      className: data.name,
      ['folder.className']: data.name,
      ['folder.classId']: data.value,
      ['folder.members']: data.list,
      show: false,
    });
  },
  // 单选框 end



  // 获得input值
  handleChange(e) {
    console.log(e.detail.value);
    let value = e.detail.value
    value = value.replace(/^\s*/, "");
    console.log('value', value);
    this.setData({
      ['folder.name']: value
    })
  },
  // 上传附件
  addfile() {
    if (that.data.folder.name == '') {
      App.toast.showToast('文件夹名称不得为空!')
      return
    }
    that.setData({
      btnloading: true
    })
    wx.chooseMessageFile({
      count: 20,
      type: 'all',
      success(res) {
        console.log(res);
        let data = res.tempFiles
        console.log(data);
        const uploadTasks = data.map((file, index) => {
          let cloudPath = "folder/" + that.data.folder.name + "/" + that.data.UserInfo.nickName + "/" + file.name
          return wx.cloud.uploadFile({
            cloudPath: cloudPath,
            filePath: file.path
          });
        });
        Promise.all(uploadTasks)
          .then(res => {
            let list = []
            res.forEach((item, index) => {
              list.push({
                name: data[index].name,
                size: (data[index].size / 1024 / 1024).toFixed(2),
                id: item.fileID,
                type: data[index].type,
                timeTs: Date.now(),
                UploadUsers: that.data.UserInfo.nickName,
                UploadUsersId: that.data.UserInfo.account,
                fileId: Date.now() + index
              })
            })
            let fileList = that.data.folder.file
            list.forEach(item => {
              fileList.push(item)
            })
            console.log('fileList', fileList);
            that.setData({
              ['folder.file']: fileList,
              btnloading: false
            })
          })
          .catch(e => {
            that.setData({
              btnloading: false
            })
            console.log(e);
          });
      },
      fail: function (res) {
        that.setData({
          btnloading: false
        })
      }
    })
  },


  // 删除附件
  removefileName(e) {
    const {
      index
    } = e.currentTarget.dataset
    console.log(index);
    let fileList = that.data.folder.file
    console.log(fileList.splice(index, 1));
    that.setData({
      ['folder.file']: fileList,
    })
  },

  // 获得班级
  getMyclass() {
    db.collection('myclass').where({
        Administrator: that.data.UserInfo.account
      })
      .get({
        success: function (res) {
          console.log(res.data)
          that.setData({
            class: res.data,
            loading: false,
          })
        }
      })
  },


  // 效验
  check() {
    let folder = that.data.folder
    console.log('folder', folder);
    if (folder.name == '') {
      App.toast.showToast('请输入文件夹名称')
      return
    }
    // 如果是私有，那么应该绑定班级
    if (folder.category === 'Private' && folder.className == '') {
      App.toast.showToast('私有应该绑定班级')
      return
    }
    if (folder.file.length > 20) {
      App.toast.showToast('上传文件数量超过20', 'error')
      return
    }
    that.addFolder(folder)
  },



  addFolder(folder) {
    App.toast.showLoading('创建中')


    let folderId = (+new Date()).toString().substring(5, 13)
    db.collection('folder').add({
        data: {
          folderId: 'f' + folderId,
          name: folder.name,
          className: folder.className,
          classId: folder.classId,
          members: folder.members,
          category: folder.category,
          file: folder.file,
          creator: {
            name: that.data.UserInfo.nickName,
            account: that.data.UserInfo.account
          },
          timeTs: Date.now(),
          UploadPermission: "仅创建人",
          permissions: true,
        }
      })
      .then(res => {
        App.toast.hideLoading()
        console.log('创建成功', res);
        App.toast.showToast('创建成功，即将返回')
        setTimeout(() => {
          that.navIndex()
        }, 1500)

      })

  },
  // 跳转回去
  navIndex() {
    // 通过判断当前页面的页面栈信息，是否有上一页进行返回
    const pages = getCurrentPages()
    if (pages.length == 1) {
      console.log('已经返回来了');
    } else {
      wx.navigateBack({
        delta: 1
      })
    }

  },
})